<?php

class Router
{
	static protected $_reverse = array('admin');

	static protected $_alias = null;

	/**
	 * @var Request
	 */
	static public function dispatch($request)
	{
		$path = $request -> getPath();

		$base = Agilet::getAppUrl();

		if ($base && $base != '/')
		{
			$path = str_replace($base, '', $path);
		}

		$path = trim($path, '/');

		if ($path == null)
		{
			$path = 'home';
		}

		if (null == self::$_alias)
		{
			self::$_alias = Agilet::loadConfig('redirect.php');
		}
        

		if (isset(self::$_alias[$path]))
		{
			$path = self::$_alias[$path];
		}

		$found = self::__find($path);

		// loop back this action to find correct path.

		if (!$found)
		{
			$found = 'notfound';
		}

		$request -> setController($found);
	}

	/**
	 * FIND path or not
	 * admin/dashboard					=> classes/system/controller/admin/dashboard.php
	 * home								=> classes/system/controller/home.php
	 * admin/video 						=> classes/video/controller/admin/video.php
	 * admin/photo/upload				=> classes/video/controller/admin/photo/upload.php
	 * sc/auth?service/facebook 		=> classes/social-connect/controller/auth.php
	 * {service:facebook}
	 * client/products/license			=> classes/client/products/license.php
	 * admin/photo/manage/category 		=>
	 * classes/photo/controller/admin/manage/category
	 * photo/mangage/category			=> classes/photo/controller/manage/category
	 *
	 * need a clan fest from url_path =>controller paths[path1, path2, path3,
	 * path4] then we can nest from fast to faster query.
	 */
	protected static function __find($full_path)
	{

		$arr = explode('/', $full_path);

		// rorate from 3 to 6.
		$len = count($arr);
		$max = 6;
		$end = $len > $max ? $max : $len;
		$start = 0;

		do
		{
			$path = implode('/', array_slice($arr, 0, $end));
			
			if (isset(self::$_alias[$path]))
			{
				$path = self::$_alias[$path];
			}

			$file = AGILET_APPLICATION_PATH . '/controller/' . $path . '.php';

			if (file_exists($file))
			{
				require_once $file;
				return $path;
			}
			
			$file = AGILET_APPLICATION_PATH . '/controller/' . $path . '/index.php';
			
			if (file_exists($file))
			{
				require_once $file;
				return $path;
			}

		}
		while(-- $end > 0);
		return FALSE;
	}

	/**
	 * revert path to match correct
	 * @param string
	 * @return string/null
	 */
	static public function revertPath($path, &$module)
	{
		$pos = strpos($path, '/');
		$module = substr($path, 0, $pos);
		$path = substr($path, $pos + 1);
		return $path;
	}

	static public function sanitizeControllerClass($path, &$class)
	{

		$class = 'Controller_' . implode('_', array_map('inflect', explode('/', $path)));
		return $class;
	}

}
